# coding=utf-8
from django.db.models.query_utils import Q
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from trp.models import *
from utils.JsonResponse import *
from django.shortcuts import render_to_response
import datetime
from django.core.exceptions import ObjectDoesNotExist
import json
from django.http.response import HttpResponse
from utils.decorators import *
import time
from django.db.models import Min,Max,Sum 
from website.settings import LOGGER as logger


@login_required
def main(request):
    account = request.user.account
    if account.is_admin():
        return log_response(request,'trp/operationlog_admin.html',{})    
    else:
        return JsonResponseBadrequest({"message":str("权限不足")})

def log_response(request,html,dic):
    return render_to_response(html, dict({'user' : request.user, 'page' : 'log'},**dic))

def get_logs(request):
    account = request.user.account
    if not account.is_admin():
        return JsonResponseBadrequest({"message":str("权限不足")})
    params = json.loads(request.body)
    search_text = params.get("search_text", "")  # 模糊搜索
    start = params.get("start")
    end = params.get("end")
    type=params.get("type")
    order_by = params.get("orderBy", "-id")
    pageSize = int(params.get("pageSize", 30))
    pageNo = int(params.get("pageNo", 1))
    args = []
    kwargs = {}
    order = []
    if start:
        start = datetime.datetime.strptime(start,"%Y-%m-%d").date()
        end = datetime.datetime.strptime(end,"%Y-%m-%d").date()
        end=datetime.datetime(end.year,end.month,end.day,23,59,59)
        args.append(Q(time__range=(start,end)))
    if search_text:
        args.append(Q(operation__icontains=search_text) | Q(object__icontains=search_text)|Q(user__username__icontains=search_text));
    if order_by:
        order.append(order_by)
    list = OperationLog.objects.filter(*args, **kwargs).order_by(*order).distinct()
    paginator = Paginator(list, pageSize)
    try:
        pageObj = paginator.page(pageNo)
    except PageNotAnInteger:
        pageObj = paginator.page(1)
    except EmptyPage:
        pageObj = paginator.page(paginator.num_pages)
    results = {}
    datalist=[]
    for obj in pageObj.object_list:
        data={}
        data["username"]=obj.user.username
        data["time"]=obj.time
        data["operation"]=obj.operation
        data["objectname"]=obj.object
        data["objectid"]=obj.object_id
        data["details"]=obj.details
        datalist.append(data)
    results['bodyData'] = datalist
    results["pageNo"] = pageNo
    results["pageSize"] = pageSize
    results["totalCount"] = paginator.count
    return JsonResponse(results)    